package bill.study.javaPuzzlers.classy;

/**
 * If the time and space cost to initialize a field is low or the field is
 * required in every execution of the program, eager initialization is
 * appropriate. If the cost is high and the field might not be required in some
 * executions, lazy initialization may be preferable. Also, lazy initialization
 * may be necessary to break a cycle in class or instance initialization.
 * 
 * class initialization executes static initializers in the order they appear in
 * the source.
 * 
 * do you best to keep the class initialization sequence simple.
 * 
 * @author yangliu
 * 
 */
class Cache {
	static {
		initializeIfNecessary();
	}
	private static int sum;

	public static int getSum() {
		initializeIfNecessary();
		return sum;
	}

	private static boolean initialized = false;

	private static synchronized void initializeIfNecessary() {
		if (!initialized) {
			for (int i = 0; i < 100; i++) {
				sum += i;
				initialized = true;
			}
		}
	}
}

public class SumFunClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
